"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import { Checkbox } from "@/components/ui/checkbox"
import { Sparkles, Twitter, Facebook, ChevronDown, ChevronUp, Loader2, AlertTriangle, Globe } from "lucide-react"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"

interface SlimeRecipe {
  name: string
  baseIngredients: string[]
  addIns: string[]
  activator: string[]
  steps: string[]
  tips: string[]
  safetyNote: string
}

const slimeRecipes: SlimeRecipe[] = [
  {
    name: "Galaxy Glitter Slime",
    baseIngredients: ["4 oz White School Glue", "2 tbsp Shaving Cream", "1 tsp Lotion"],
    addIns: ["Purple Food Coloring", "Silver Glitter", "Holographic Glitter"],
    activator: ["1-2 tbsp Contact Lens Solution", "1/2 tsp Baking Soda"],
    steps: [
      "Mix glue and shaving cream in a large bowl",
      "Add lotion and mix until smooth",
      "Add food coloring and glitter, stir well",
      "Slowly add contact lens solution while mixing until slime forms",
    ],
    tips: ["Add more contact lens solution if too sticky!", "Store in airtight container for up to 1 week"],
    safetyNote: "Adult supervision recommended. Wash hands after use.",
  },
  {
    name: "Fluffy Cloud Slime",
    baseIngredients: ["6 oz Clear Glue", "3 cups Shaving Cream", "1 tbsp Lotion"],
    addIns: ["White Food Coloring", "Vanilla Scent", "Fake Snow"],
    activator: ["2 tbsp Saline Solution", "1 tsp Baking Soda"],
    steps: [
      "Pour clear glue into mixing bowl",
      "Add shaving cream gradually while mixing",
      "Mix in lotion and scent",
      "Add activator slowly until perfect consistency",
    ],
    tips: ["The more shaving cream, the fluffier your slime!", "Perfect for stress relief"],
    safetyNote: "Keep away from fabric and carpet. Adult supervision required.",
  },
  {
    name: "Unicorn Dreams Slime",
    baseIngredients: ["5 oz White Glue", "2 tbsp Shaving Cream", "1 tsp Baby Oil"],
    addIns: ["Pink & Purple Food Coloring", "Rainbow Glitter", "Unicorn Charms"],
    activator: ["1.5 tbsp Contact Lens Solution", "1/2 tsp Baking Soda"],
    steps: [
      "Mix base ingredients until smooth",
      "Create marble effect with food coloring",
      "Add glitter and charms",
      "Activate with contact lens solution",
    ],
    tips: ["Swirl colors gently for marble effect", "Add charms after slime is ready"],
    safetyNote: "Small parts - not suitable for children under 3 years.",
  },
  {
    name: "Ocean Wave Slime",
    baseIngredients: ["4 oz Clear Glue", "1 tbsp Shaving Cream", "1 tsp Glycerin"],
    addIns: ["Blue Food Coloring", "Sea Salt", "Ocean Scent", "Blue Glitter"],
    activator: ["2 tbsp Saline Solution", "1/2 tsp Baking Soda"],
    steps: [
      "Mix clear glue with shaving cream",
      "Add glycerin for extra stretch",
      "Create ocean waves with blue coloring",
      "Activate slowly for perfect texture",
    ],
    tips: ["Glycerin makes slime extra stretchy!", "Store in cool place"],
    safetyNote: "Wash hands thoroughly after playing.",
  },
  {
    name: "Chocolate Scented Slime",
    baseIngredients: ["5 oz White Glue", "2 tbsp Shaving Cream", "1 tbsp Lotion"],
    addIns: ["Brown Food Coloring", "Chocolate Scent", "Brown Foam Beads"],
    activator: ["1.5 tbsp Contact Lens Solution", "1 tsp Baking Soda"],
    steps: [
      "Combine all base ingredients",
      "Add brown coloring gradually",
      "Mix in chocolate scent and beads",
      "Activate until desired consistency",
    ],
    tips: ["Don't eat - it's not real chocolate!", "Great for sensory play"],
    safetyNote: "Not edible. Keep away from mouth and eyes.",
  },
]

interface FilterCategory {
  id: string
  name: string
  required: boolean
  maxSelections: number
  options: FilterOption[]
}

interface FilterOption {
  id: string
  label: string
  description?: string
  warning?: string
  checked: boolean
}

const filterCategories: FilterCategory[] = [
  {
    id: "base",
    name: "Base Materials",
    required: true,
    maxSelections: 1,
    options: [
      { id: "white-glue", label: "White Glue (PVA)", description: "Classic choice, opaque finish", checked: false },
      {
        id: "clear-glue",
        label: "Clear Glue",
        description: "Transparent, great for see-through effects",
        checked: false,
      },
      {
        id: "liquid-starch",
        label: "Liquid Starch",
        description: "Alternative base, creates firm texture",
        checked: false,
      },
      {
        id: "shampoo-salt",
        label: "Shampoo + Salt",
        description: "No-glue alternative, budget-friendly",
        checked: false,
      },
      {
        id: "cornstarch-water",
        label: "Cornstarch + Water",
        description: "Natural alternative, safe for kids",
        checked: false,
      },
      { id: "hair-gel-soap", label: "Hair Gel + Hand Soap", description: "Creative no-glue option", checked: false },
      { id: "shaving-cream", label: "Shaving Cream Base", description: "Creates extra fluffy texture", checked: false },
      {
        id: "contact-solution",
        label: "Contact Lens Solution",
        description: "Safe activator that can also be base",
        checked: false,
      },
    ],
  },
  {
    id: "activator",
    name: "Activators",
    required: true,
    maxSelections: 1,
    options: [
      {
        id: "borax-water",
        label: "Borax Water",
        description: "Traditional activator",
        warning: "Adult supervision required",
        checked: false,
      },
      {
        id: "contact-lens-solution",
        label: "Contact Lens Solution",
        description: "Contains boric acid, safer option",
        checked: false,
      },
      {
        id: "baking-soda-water",
        label: "Baking Soda + Hot Water",
        description: "Safe household activator",
        checked: false,
      },
      {
        id: "laundry-detergent",
        label: "Laundry Detergent",
        description: "Liquid detergent works as activator",
        checked: false,
      },
      { id: "salt-water", label: "Salt Water", description: "Kid-friendly, very safe", checked: false },
      {
        id: "liquid-starch-activator",
        label: "Liquid Starch",
        description: "Gentle activator for sensitive skin",
        checked: false,
      },
    ],
  },
  {
    id: "texture",
    name: "Texture & Feel",
    required: false,
    maxSelections: 2,
    options: [
      { id: "shaving-foam", label: "Shaving Foam", description: "More foam = fluffier slime", checked: false },
      { id: "glycerin", label: "Glycerin", description: "Prevents stickiness, adds elasticity", checked: false },
      { id: "lotion", label: "Lotion", description: "Smooth texture, prevents sticking to hands", checked: false },
      { id: "foam-balls", label: "Foam Balls", description: "Crunchy, satisfying texture", checked: false },
      { id: "sugar-granules", label: "Sugar Granules", description: "Natural grainy texture", checked: false },
      { id: "plastic-beads", label: "Micro Plastic Beads", description: "Smooth granular feel", checked: false },
      { id: "mint-oil", label: "Mint Essential Oil", description: "Cool, refreshing sensation", checked: false },
    ],
  },
  {
    id: "colors",
    name: "Colors & Themes",
    required: false,
    maxSelections: 1,
    options: [
      { id: "red-coloring", label: "Red Food Coloring", description: "Classic vibrant red", checked: false },
      { id: "blue-coloring", label: "Blue Food Coloring", description: "Ocean blue shade", checked: false },
      { id: "green-coloring", label: "Green Food Coloring", description: "Nature green tone", checked: false },
      { id: "yellow-coloring", label: "Yellow Food Coloring", description: "Sunny yellow bright", checked: false },
      { id: "purple-coloring", label: "Purple Food Coloring", description: "Royal purple hue", checked: false },
      {
        id: "glow-pigment",
        label: "Glow-in-Dark Pigment",
        description: "Charges in light, glows in dark",
        checked: false,
      },
      { id: "gold-glitter", label: "Gold Metallic Glitter", description: "Luxurious golden sparkle", checked: false },
      {
        id: "silver-glitter",
        label: "Silver Metallic Glitter",
        description: "Shimmering silver effect",
        checked: false,
      },
      {
        id: "thermochromic",
        label: "Color-Changing Pigment",
        description: "Changes color with temperature",
        checked: false,
      },
      {
        id: "galaxy-theme",
        label: "Galaxy Theme Pack",
        description: "Deep blue + black + silver glitter",
        checked: false,
      },
      {
        id: "unicorn-theme",
        label: "Unicorn Theme Pack",
        description: "Pink + purple + rainbow glitter",
        checked: false,
      },
    ],
  },
  {
    id: "addins",
    name: "Special Add-ins",
    required: false,
    maxSelections: 5,
    options: [
      {
        id: "holographic-glitter",
        label: "Holographic Glitter",
        description: "Rainbow sparkle effect",
        checked: false,
      },
      {
        id: "colored-sugar",
        label: "Colored Sugar Crystals",
        description: "Edible decoration (don't eat slime!)",
        checked: false,
      },
      { id: "glow-stars", label: "Fluorescent Mini Stars", description: "Tiny glowing star shapes", checked: false },
      { id: "fine-sand", label: "Fine Sand", description: "Beach-like gritty texture", checked: false },
      { id: "fluff-powder", label: "Fluff Powder", description: "Soft, fuzzy cloud texture", checked: false },
      { id: "vanilla-scent", label: "Vanilla Essential Oil", description: "Sweet, comforting aroma", checked: false },
      {
        id: "watermelon-scent",
        label: "Watermelon Fragrance",
        description: "Fresh, fruity summer scent",
        checked: false,
      },
      { id: "blueberry-scent", label: "Blueberry Fragrance", description: "Sweet berry aroma", checked: false },
      {
        id: "magnetic-powder",
        label: "Iron Oxide Powder",
        description: "Creates magnetic slime properties",
        checked: false,
      },
      { id: "confetti", label: "Biodegradable Confetti", description: "Festive paper pieces", checked: false },
    ],
  },
]

export default function SlimeRecipeGenerator() {
  const [selectedFilters, setSelectedFilters] = useState<{ [key: string]: string[] }>({
    base: [],
    activator: [],
    texture: [],
    colors: [],
    addins: [],
  })
  const [currentRecipe, setCurrentRecipe] = useState<SlimeRecipe | null>(null)
  const [isGenerating, setIsGenerating] = useState(false)
  const [showAdvanced, setShowAdvanced] = useState(false)
  const [language, setLanguage] = useState("EN")

  // Add validation function
  const validateSelections = () => {
    const errors: string[] = []

    filterCategories.forEach((category) => {
      const selected = selectedFilters[category.id] || []
      if (category.required && selected.length === 0) {
        errors.push(`Please select a ${category.name.toLowerCase()}`)
      }
      if (selected.length > category.maxSelections) {
        errors.push(`Too many ${category.name.toLowerCase()} selected (max: ${category.maxSelections})`)
      }
    })

    return errors
  }

  // Update the generateRecipe function to use selected filters
  const generateRecipe = async () => {
    const errors = validateSelections()
    if (errors.length > 0) {
      alert(errors.join("\n"))
      return
    }

    setIsGenerating(true)
    await new Promise((resolve) => setTimeout(resolve, 1500))

    // Generate recipe based on selected filters
    const customRecipe = generateCustomRecipe(selectedFilters)
    setCurrentRecipe(customRecipe)
    setIsGenerating(false)
  }

  // Add custom recipe generation function
  const generateCustomRecipe = (filters: { [key: string]: string[] }): SlimeRecipe => {
    const baseOption = filterCategories[0].options.find((opt) => filters.base?.includes(opt.id))
    const activatorOption = filterCategories[1].options.find((opt) => filters.activator?.includes(opt.id))

    const recipeName = generateRecipeName(filters)

    return {
      name: recipeName,
      baseIngredients: generateBaseIngredients(filters),
      addIns: generateAddIns(filters),
      activator: generateActivatorList(filters),
      steps: generateSteps(filters),
      tips: generateTips(filters),
      safetyNote: generateSafetyNote(filters),
    }
  }

  // Helper functions for recipe generation
  const generateRecipeName = (filters: { [key: string]: string[] }): string => {
    const themes = {
      "galaxy-theme": "Cosmic Galaxy",
      "unicorn-theme": "Magical Unicorn",
      "glow-pigment": "Glow Master",
      "gold-glitter": "Golden Treasure",
      "silver-glitter": "Silver Storm",
    }

    const colorNames = {
      "red-coloring": "Ruby Red",
      "blue-coloring": "Ocean Blue",
      "green-coloring": "Forest Green",
      "purple-coloring": "Royal Purple",
    }

    const textureNames = {
      "shaving-foam": "Fluffy Cloud",
      "foam-balls": "Crunchy Bubble",
      "magnetic-powder": "Magnetic Wonder",
    }

    // Check for theme first
    for (const [key, name] of Object.entries(themes)) {
      if (filters.colors?.includes(key)) return `${name} Slime`
    }

    // Check for special textures
    for (const [key, name] of Object.entries(textureNames)) {
      if (filters.texture?.includes(key) || filters.addins?.includes(key)) return `${name} Slime`
    }

    // Check for colors
    for (const [key, name] of Object.entries(colorNames)) {
      if (filters.colors?.includes(key)) return `${name} Slime`
    }

    return "Custom Amazing Slime"
  }

  const generateBaseIngredients = (filters: { [key: string]: string[] }): string[] => {
    const ingredients: string[] = []

    if (filters.base?.includes("white-glue")) ingredients.push("4 oz White School Glue")
    if (filters.base?.includes("clear-glue")) ingredients.push("4 oz Clear Glue")
    if (filters.base?.includes("shampoo-salt")) ingredients.push("3 tbsp Thick Shampoo", "1 tsp Table Salt")
    if (filters.base?.includes("cornstarch-water")) ingredients.push("1/2 cup Cornstarch", "1/4 cup Water")
    if (filters.base?.includes("shaving-cream")) ingredients.push("2 cups Shaving Cream")

    if (filters.texture?.includes("lotion")) ingredients.push("1 tbsp Hand Lotion")
    if (filters.texture?.includes("glycerin")) ingredients.push("1 tsp Glycerin")

    return ingredients
  }

  const generateAddIns = (filters: { [key: string]: string[] }): string[] => {
    const addIns: string[] = []

    // Colors
    if (filters.colors?.includes("red-coloring")) addIns.push("Red Food Coloring")
    if (filters.colors?.includes("blue-coloring")) addIns.push("Blue Food Coloring")
    if (filters.colors?.includes("galaxy-theme"))
      addIns.push("Deep Blue Coloring", "Black Food Coloring", "Silver Glitter")
    if (filters.colors?.includes("unicorn-theme")) addIns.push("Pink Coloring", "Purple Coloring", "Rainbow Glitter")
    if (filters.colors?.includes("glow-pigment")) addIns.push("Glow-in-Dark Powder")

    // Textures
    if (filters.texture?.includes("shaving-foam")) {
      addIns.push("Extra Shaving Foam")
    }
    if (filters.texture?.includes("foam-balls")) {
      addIns.push("Foam Beads")
    }
    if (filters.texture?.includes("mint-oil")) {
      addIns.push("2-3 drops Mint Essential Oil")
    }

    // Special add-ins
    if (filters.addins?.includes("holographic-glitter")) addIns.push("Holographic Glitter")
    if (filters.addins?.includes("vanilla-scent")) addIns.push("Vanilla Essential Oil")
    if (filters.addins?.includes("magnetic-powder")) addIns.push("Iron Oxide Powder")
    if (filters.addins?.includes("fine-sand")) addIns.push("Fine Craft Sand")

    return addIns
  }

  const generateActivatorList = (filters: { [key: string]: string[] }): string[] => {
    if (filters.activator?.includes("borax-water")) return ["1 tsp Borax", "1 cup Warm Water"]
    if (filters.activator?.includes("contact-lens-solution"))
      return ["2 tbsp Contact Lens Solution", "1/2 tsp Baking Soda"]
    if (filters.activator?.includes("baking-soda-water")) return ["1 tbsp Baking Soda", "2 tbsp Hot Water"]
    if (filters.activator?.includes("salt-water")) return ["2 tbsp Salt", "1/4 cup Warm Water"]
    if (filters.activator?.includes("laundry-detergent")) return ["1-2 tbsp Liquid Laundry Detergent"]

    return ["2 tbsp Contact Lens Solution", "1/2 tsp Baking Soda"]
  }

  const generateSteps = (filters: { [key: string]: string[] }): string[] => {
    const steps: string[] = []

    // Base mixing
    if (filters.base?.includes("white-glue") || filters.base?.includes("clear-glue")) {
      steps.push("Pour glue into a large mixing bowl")
    } else if (filters.base?.includes("shampoo-salt")) {
      steps.push("Mix shampoo and salt in a bowl until thick")
    } else if (filters.base?.includes("cornstarch-water")) {
      steps.push("Slowly mix cornstarch with water until smooth")
    }

    // Add texture ingredients
    if (filters.texture?.includes("shaving-foam")) {
      steps.push("Gradually fold in shaving foam for fluffy texture")
    }
    if (filters.texture?.includes("lotion") || filters.texture?.includes("glycerin")) {
      steps.push("Mix in lotion/glycerin for smooth consistency")
    }

    // Add colors and effects
    if (filters.colors?.length > 0 || filters.addins?.length > 0) {
      steps.push("Add coloring and decorative elements, mix gently")
    }

    // Activation
    if (filters.activator?.includes("borax-water")) {
      steps.push("SLOWLY add borax water while stirring continuously")
    } else {
      steps.push("Add activator gradually while mixing until slime forms")
    }

    steps.push("Knead with hands until desired consistency is reached")

    return steps
  }

  const generateTips = (filters: { [key: string]: string[] }): string[] => {
    const tips: string[] = []

    if (filters.activator?.includes("borax-water")) {
      tips.push("Add borax water very slowly - too much will make slime rubbery!")
    }
    if (filters.texture?.includes("shaving-foam")) {
      tips.push("More shaving foam = fluffier slime, but harder to activate")
    }
    if (filters.addins?.includes("magnetic-powder")) {
      tips.push("Use a strong magnet to make your slime move and dance!")
    }
    if (filters.colors?.includes("glow-pigment")) {
      tips.push("Charge under bright light for 10 minutes for best glow effect")
    }

    tips.push("Store in airtight container to prevent drying out")
    tips.push("If too sticky, add more activator bit by bit")

    return tips
  }

  const generateSafetyNote = (filters: { [key: string]: string[] }): string => {
    let note = "Always wash hands before and after playing. "

    if (filters.activator?.includes("borax-water")) {
      note += "ADULT SUPERVISION REQUIRED when using borax. "
    }
    if (filters.addins?.includes("mint-oil")) {
      note += "Use essential oils sparingly - too much can irritate skin. "
    }
    if (filters.texture?.includes("fine-sand")) {
      note += "Keep away from eyes and mouth when using sand. "
    }

    note += "Not suitable for children under 3 years."

    return note
  }

  // Update the filter selection handler
  const handleFilterChange = (categoryId: string, optionId: string, checked: boolean) => {
    setSelectedFilters((prev) => {
      const category = filterCategories.find((cat) => cat.id === categoryId)
      if (!category) return prev

      const currentSelections = prev[categoryId] || []

      if (checked) {
        // Check if we can add more selections
        if (currentSelections.length >= category.maxSelections) {
          // If single selection category, replace the selection
          if (category.maxSelections === 1) {
            return { ...prev, [categoryId]: [optionId] }
          }
          // Otherwise, don't add
          return prev
        }
        return { ...prev, [categoryId]: [...currentSelections, optionId] }
      } else {
        return { ...prev, [categoryId]: currentSelections.filter((id) => id !== optionId) }
      }
    })
  }

  const shareRecipe = (platform: string) => {
    if (!currentRecipe) return

    const text = `Check out this amazing ${currentRecipe.name} recipe! 🌟`
    const url = window.location.href

    if (platform === "twitter") {
      window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(url)}`)
    } else if (platform === "facebook") {
      window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-pink-100 via-purple-50 to-blue-100">
      {/* Header */}
      <header className="bg-white/80 backdrop-blur-sm border-b border-pink-200 sticky top-0 z-50">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2">
              <Sparkles className="h-8 w-8 text-pink-500" />
              <div>
                <h1 className="text-2xl md:text-3xl font-bold bg-gradient-to-r from-pink-500 to-purple-600 bg-clip-text text-transparent">
                  Free Slime Recipe Generator
                </h1>
                <p className="text-sm text-gray-600">Create custom DIY slime recipes in seconds!</p>
              </div>
            </div>

            <div className="flex items-center space-x-4">
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="outline" size="sm" className="flex items-center space-x-1 bg-transparent">
                    <Globe className="h-4 w-4" />
                    <span>
                      {language === "EN" ? "🇺🇸" : "🇪🇸"} {language}
                    </span>
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent>
                  <DropdownMenuItem onClick={() => setLanguage("EN")}>🇺🇸 English</DropdownMenuItem>
                  <DropdownMenuItem onClick={() => setLanguage("ES")}>🇪🇸 Español</DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>

          <nav className="mt-4">
            <div className="flex space-x-6 text-sm">
              <a href="#" className="text-gray-700 hover:text-pink-600 transition-colors">
                Home
              </a>
              <a href="#" className="text-gray-700 hover:text-pink-600 transition-colors">
                Slime Safety
              </a>
              <a href="#" className="text-gray-700 hover:text-pink-600 transition-colors">
                Popular Ingredients
              </a>
            </div>
          </nav>
        </div>
      </header>

      {/* Main Content */}
      <main className="container mx-auto px-4 py-8">
        {/* Hero Section */}
        <div className="text-center mb-12">
          <div className="relative inline-block">
            <div className="absolute -inset-1 bg-gradient-to-r from-pink-400 to-purple-400 rounded-lg blur opacity-25"></div>
            <h2 className="relative text-4xl md:text-6xl font-bold text-gray-800 mb-4">Make Amazing Slime! 🌟</h2>
          </div>
          <p className="text-lg text-gray-600 max-w-2xl mx-auto">
            Generate unlimited DIY slime recipes with safe, easy-to-find ingredients. Perfect for kids' science projects
            and creative fun!
          </p>
        </div>

        {/* Core Tool Area */}
        <div className="max-w-4xl mx-auto">
          {/* Comprehensive Filters */}
          <Card className="mb-8 border-2 border-pink-200">
            <CardHeader>
              <CardTitle className="flex items-center justify-between">
                <span>Customize Your Perfect Slime Recipe</span>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setShowAdvanced(!showAdvanced)}
                  className="text-purple-600"
                >
                  {showAdvanced ? "Simple View" : "Advanced Options"}
                  {showAdvanced ? <ChevronUp className="ml-1 h-4 w-4" /> : <ChevronDown className="ml-1 h-4 w-4" />}
                </Button>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              {filterCategories.map((category, categoryIndex) => {
                // Show first 2 categories always, others only in advanced mode
                if (!showAdvanced && categoryIndex > 1) return null

                return (
                  <div key={category.id} className="space-y-3">
                    <div className="flex items-center space-x-2">
                      <h3 className="font-semibold text-lg text-gray-800">{category.name}</h3>
                      {category.required && (
                        <Badge variant="destructive" className="text-xs">
                          Required
                        </Badge>
                      )}
                      <span className="text-sm text-gray-500">
                        (Select {category.maxSelections === 1 ? "1" : `up to ${category.maxSelections}`})
                      </span>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                      {category.options.map((option) => {
                        const isSelected = selectedFilters[category.id]?.includes(option.id) || false
                        const isDisabled =
                          !isSelected && (selectedFilters[category.id]?.length || 0) >= category.maxSelections

                        return (
                          <div
                            key={option.id}
                            className={`border rounded-lg p-3 cursor-pointer transition-all ${
                              isSelected
                                ? "border-purple-500 bg-purple-50"
                                : isDisabled
                                  ? "border-gray-200 bg-gray-50 opacity-50 cursor-not-allowed"
                                  : "border-gray-200 hover:border-purple-300 hover:bg-purple-25"
                            }`}
                            onClick={() => !isDisabled && handleFilterChange(category.id, option.id, !isSelected)}
                          >
                            <div className="flex items-start space-x-2">
                              <Checkbox checked={isSelected} disabled={isDisabled} className="mt-0.5" />
                              <div className="flex-1 min-w-0">
                                <div className="flex items-center space-x-2">
                                  <span className="font-medium text-sm">{option.label}</span>
                                  {option.warning && <AlertTriangle className="h-4 w-4 text-orange-500" />}
                                </div>
                                {option.description && (
                                  <p className="text-xs text-gray-600 mt-1">{option.description}</p>
                                )}
                                {option.warning && (
                                  <p className="text-xs text-orange-600 mt-1 font-medium">⚠️ {option.warning}</p>
                                )}
                              </div>
                            </div>
                          </div>
                        )
                      })}
                    </div>
                  </div>
                )
              })}

              {!showAdvanced && (
                <div className="text-center pt-4 border-t border-gray-200">
                  <p className="text-sm text-gray-600 mb-2">
                    Want more options? Click "Advanced Options" above for colors, textures, and special add-ins!
                  </p>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Generation Button */}
          <div className="text-center mb-8">
            <Button
              onClick={generateRecipe}
              disabled={isGenerating}
              className="bg-gradient-to-r from-pink-500 to-purple-600 hover:from-pink-600 hover:to-purple-700 text-white font-bold py-4 px-8 rounded-full text-lg shadow-lg hover:shadow-xl transform hover:-translate-y-1 transition-all duration-200"
              size="lg"
            >
              {isGenerating ? (
                <>
                  <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                  Generating Magic...
                </>
              ) : (
                <>
                  <Sparkles className="mr-2 h-5 w-5" />
                  Generate My Slime Recipe!
                </>
              )}
            </Button>
          </div>

          {/* Recipe Results */}
          {currentRecipe && (
            <Card className="border-2 border-purple-200 shadow-xl">
              <CardHeader className="bg-gradient-to-r from-pink-50 to-purple-50">
                <div className="flex items-center justify-between">
                  <CardTitle className="text-2xl text-purple-800 flex items-center">
                    <Sparkles className="mr-2 h-6 w-6" />
                    {currentRecipe.name}
                  </CardTitle>
                  <div className="flex space-x-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => shareRecipe("twitter")}
                      className="text-blue-500 hover:bg-blue-50"
                    >
                      <Twitter className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => shareRecipe("facebook")}
                      className="text-blue-600 hover:bg-blue-50"
                    >
                      <Facebook className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="p-6">
                <div className="grid md:grid-cols-3 gap-6 mb-6">
                  <div>
                    <h3 className="font-semibold text-lg mb-3 text-pink-700">Base Ingredients</h3>
                    <ul className="space-y-2">
                      {currentRecipe.baseIngredients.map((ingredient, index) => (
                        <li key={index} className="flex items-center">
                          <Badge variant="secondary" className="mr-2">
                            Base
                          </Badge>
                          <span className="text-sm">{ingredient}</span>
                        </li>
                      ))}
                    </ul>
                  </div>

                  <div>
                    <h3 className="font-semibold text-lg mb-3 text-purple-700">Add-ins</h3>
                    <ul className="space-y-2">
                      {currentRecipe.addIns.map((addIn, index) => (
                        <li key={index} className="flex items-center">
                          <Badge variant="outline" className="mr-2">
                            Fun
                          </Badge>
                          <span className="text-sm">{addIn}</span>
                        </li>
                      ))}
                    </ul>
                  </div>

                  <div>
                    <h3 className="font-semibold text-lg mb-3 text-blue-700">Activator</h3>
                    <ul className="space-y-2">
                      {currentRecipe.activator.map((activator, index) => (
                        <li key={index} className="flex items-center">
                          <Badge className="mr-2 bg-blue-100 text-blue-800">Active</Badge>
                          <span className="text-sm">{activator}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>

                <Separator className="my-6" />

                <div className="mb-6">
                  <h3 className="font-semibold text-lg mb-3 text-gray-800">Step-by-Step Instructions</h3>
                  <ol className="space-y-3">
                    {currentRecipe.steps.map((step, index) => (
                      <li key={index} className="flex items-start">
                        <span className="bg-gradient-to-r from-pink-500 to-purple-600 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold mr-3 mt-0.5">
                          {index + 1}
                        </span>
                        <span className="text-gray-700">{step}</span>
                      </li>
                    ))}
                  </ol>
                </div>

                <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-4">
                  <h4 className="font-semibold text-yellow-800 mb-2 flex items-center">
                    <Sparkles className="mr-2 h-4 w-4" />
                    Pro Tips
                  </h4>
                  <ul className="space-y-1">
                    {currentRecipe.tips.map((tip, index) => (
                      <li key={index} className="text-sm text-yellow-700">
                        • {tip}
                      </li>
                    ))}
                  </ul>
                </div>

                <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                  <h4 className="font-semibold text-red-800 mb-2 flex items-center">
                    <AlertTriangle className="mr-2 h-4 w-4" />
                    Safety First
                  </h4>
                  <p className="text-sm text-red-700">{currentRecipe.safetyNote}</p>
                </div>
              </CardContent>
            </Card>
          )}

          {/* SEO Content */}
          <div className="mt-12 text-center">
            <p className="text-gray-600 max-w-3xl mx-auto">
              Explore hundreds of slime recipes with glue, saline solution, or cornstarch. Perfect for kids' science
              projects, sensory play, and creative activities. Learn how to make slime without borax using safe,
              household ingredients.
            </p>
          </div>
        </div>
      </main>

      {/* Footer */}
      <footer className="bg-white/80 backdrop-blur-sm border-t border-pink-200 mt-16">
        <div className="container mx-auto px-4 py-8">
          <div className="text-center">
            <div className="bg-orange-50 border border-orange-200 rounded-lg p-4 mb-6 max-w-2xl mx-auto">
              <p className="text-orange-800 font-semibold flex items-center justify-center">
                <AlertTriangle className="mr-2 h-5 w-5" />
                Adult supervision recommended for all slime activities
              </p>
              <p className="text-sm text-orange-700 mt-2">
                Always wash hands after playing and keep slime away from fabric and carpet.
              </p>
            </div>

            <p className="text-gray-600 mb-4">
              Create amazing DIY slime recipes with our free generator. Safe ingredients, easy instructions, and endless
              fun for kids and families!
            </p>

            <div className="text-sm text-gray-500">
              © 2025 SlimeFun Inc. |{" "}
              <a href="#" className="hover:text-pink-600">
                Contact Us
              </a>{" "}
              |{" "}
              <a href="#" className="hover:text-pink-600">
                Privacy Policy
              </a>
            </div>
          </div>
        </div>
      </footer>
    </div>
  )
}
